package com.atguigu.security.fillter;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.Result;
import com.atguigu.common.ResultCodeEnum;
import com.atguigu.common.jwt.JwtHelper;
import com.atguigu.common.util.ResponseUtil;
import com.atguigu.security.custom.LoginUserInfoHelper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ClassName: TokenAuthenticationFilter
 * Package: com.atguigu.security.fillter
 * Description:
 *
 * @Author 蹇泽阳
 * @Create 2023/11/20 9:21
 * @Version 1.0
 */
public class TokenAuthenticationFilter extends OncePerRequestFilter {
  
  private RedisTemplate redisTemplate;
  
  public TokenAuthenticationFilter(RedisTemplate redisTemplate) {
    this.redisTemplate = redisTemplate;
  }
  
  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    // 如果是登录接口，直接放行
    if ("/admin/system/index/login".equals(request.getRequestURI())) {
      chain.doFilter(request, response);
      return;
    }
    // 判断请求头有没有token
    UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
    if (null != authentication) {
      SecurityContextHolder.getContext().setAuthentication(authentication);
      chain.doFilter(request, response);
    } else {
      ResponseUtil.out(response, Result.build(null, ResultCodeEnum.PERMISSION));
    }
  }
  
  private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
    String token = request.getHeader("token");
    logger.info("token:" + token);
    if (!StringUtils.isEmpty(token)) {
      String useruame = JwtHelper.getUsername(token);
      logger.info("useruame:" + useruame);
      if (!StringUtils.isEmpty(useruame)) {
        // 当前用户信息放到ThreadLocal里面
        LoginUserInfoHelper.setUserId(JwtHelper.getUserId(token));
        LoginUserInfoHelper.setUsername(useruame);
        // 通过用户名，从redis获取权限数据
        String authoritiesString = (String) redisTemplate.opsForValue().get(useruame);
        List<Map> mapList = JSON.parseArray(authoritiesString, Map.class);
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (Map map : mapList) {
          authorities.add(new SimpleGrantedAuthority((String)map.get("authority")));
        }
        return new UsernamePasswordAuthenticationToken(useruame, null, authorities);
        // return new UsernamePasswordAuthenticationToken(useruame, null, Collections.emptyList());
      }
    }
    return null;
  }
}
